using System.Collections.Immutable;
using System.Text;
using Newtonsoft.Json.Linq;

namespace my_console5;

public static class ElasticHelper
{
    private static readonly HttpClient _httpClient;
    private const string ElasticsearchUrl = "https://192.168.3.208:19200"; // 替换为你的ES地址
    static ElasticHelper()
    {
        var handler = new HttpClientHandler
        {
            // 跳过证书验证
            ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
        };
        _httpClient = new HttpClient(handler);
        // 设置基本认证
        var authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"elastic:hinacom"));
        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);
    }

    public static async Task<JObject> SearchAsync(string indexName, string queryJson)
    {
        var url = $"{ElasticsearchUrl}/{indexName}/_search";
        var content = new StringContent(queryJson, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync();
            return JObject.Parse(responseContent);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"请求失败: {e.Message}");
            return null;
        }
    }
}
